/**
 * 工具函数集合
 * 提供游戏中常用的辅助函数
 */
export default class Utils {
    /**
     * 生成指定范围内的随机整数
     */
    static randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    /**
     * 生成随机颜色
     */
    static randomColor() {
        const colors = [
            '#FF5722', '#E91E63', '#9C27B0', '#673AB7',
            '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4',
            '#009688', '#4CAF50', '#8BC34A', '#CDDC39',
            '#FFEB3B', '#FFC107', '#FF9800', '#FF5722'
        ];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    /**
     * 检查两个矩形是否相交
     */
    static isRectIntersect(rect1, rect2) {
        return !(rect1.x + rect1.width < rect2.x || 
                rect2.x + rect2.width < rect1.x || 
                rect1.y + rect1.height < rect2.y || 
                rect2.y + rect2.height < rect1.y);
    }

    /**
     * 检查点是否在矩形内
     */
    static isPointInRect(point, rect) {
        return point.x >= rect.x && 
               point.x <= rect.x + rect.width &&
               point.y >= rect.y && 
               point.y <= rect.y + rect.height;
    }

    /**
     * 计算两点之间的距离
     */
    static distance(point1, point2) {
        const dx = point1.x - point2.x;
        const dy = point1.y - point2.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    /**
     * 线性插值
     */
    static lerp(start, end, t) {
        return start + (end - start) * t;
    }

    /**
     * 缓动函数 - ease out
     */
    static easeOut(t) {
        return 1 - Math.pow(1 - t, 3);
    }

    /**
     * 缓动函数 - ease in out
     */
    static easeInOut(t) {
        return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    }

    /**
     * 格式化数字显示
     */
    static formatNumber(num) {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    }

    /**
     * 深拷贝对象
     */
    static deepClone(obj) {
        if (obj === null || typeof obj !== 'object') {
            return obj;
        }
        
        if (obj instanceof Date) {
            return new Date(obj.getTime());
        }
        
        if (obj instanceof Array) {
            return obj.map(item => Utils.deepClone(item));
        }
        
        const cloned = {};
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                cloned[key] = Utils.deepClone(obj[key]);
            }
        }
        return cloned;
    }

    /**
     * 洗牌算法 - Fisher-Yates
     */
    static shuffle(array) {
        const result = [...array];
        for (let i = result.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [result[i], result[j]] = [result[j], result[i]];
        }
        return result;
    }

    /**
     * 防抖函数
     */
    static debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * 节流函数
     */
    static throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }

    /**
     * 获取微信小游戏设备信息
     */
    static getDeviceInfo() {
        const systemInfo = wx.getSystemInfoSync();
        return {
            screenWidth: systemInfo.screenWidth,
            screenHeight: systemInfo.screenHeight,
            pixelRatio: systemInfo.pixelRatio,
            platform: systemInfo.platform,
            system: systemInfo.system,
            brand: systemInfo.brand,
            model: systemInfo.model
        };
    }

    /**
     * 适配横屏游戏到不同设备尺寸
     */
    static adaptToScreen(designWidth = 1334, designHeight = 750) {
        const deviceInfo = Utils.getDeviceInfo();

        console.log(`[Utils] 设备原始尺寸: ${deviceInfo.screenWidth}x${deviceInfo.screenHeight}`);

        // 对于横屏游戏，确保使用正确的屏幕尺寸
        const screenWidth = Math.max(deviceInfo.screenWidth, deviceInfo.screenHeight);
        const screenHeight = Math.min(deviceInfo.screenWidth, deviceInfo.screenHeight);

        console.log(`[Utils] 横屏调整后尺寸: ${screenWidth}x${screenHeight}`);
        console.log(`[Utils] 设计尺寸: ${designWidth}x${designHeight}`);

        const scaleX = screenWidth / designWidth;
        const scaleY = screenHeight / designHeight;
        const scale = Math.min(scaleX, scaleY);

        // 修复偏移量计算 - 对于微信小游戏，可能不需要居中偏移
        // 特别是当设备是竖屏时，坐标系统可能有所不同
        let offsetX = 0;
        let offsetY = 0;

        // 检查是否需要居中显示 - 临时禁用居中以修复坐标问题
        const needCentering = false; // 修复：禁用居中偏移

        if (needCentering) {
            offsetX = (screenWidth - designWidth * scale) / 2;
            offsetY = (screenHeight - designHeight * scale) / 2;
        }

        console.log(`[Utils] 居中显示: ${needCentering ? '启用' : '禁用'}`);
        console.log(`[Utils] 计算的偏移量: offsetX=${offsetX.toFixed(2)}, offsetY=${offsetY.toFixed(2)}`);

        // 额外的安全检查：如果偏移量过大，强制设为0
        if (offsetX > screenWidth * 0.3 || offsetY > screenHeight * 0.3) {
            console.log(`[Utils] 警告：偏移量过大，强制重置为0`);
            console.log(`[Utils] 原偏移量: offsetX=${offsetX.toFixed(2)}, offsetY=${offsetY.toFixed(2)}`);
            offsetX = 0;
            offsetY = 0;
        }

        console.log(`[Utils] 缩放比例计算: scaleX=${scaleX.toFixed(4)}, scaleY=${scaleY.toFixed(4)}, 最终scale=${scale.toFixed(4)}`);
        console.log(`[Utils] 偏移量计算: offsetX=${offsetX.toFixed(2)}, offsetY=${offsetY.toFixed(2)}`);
        console.log(`[Utils] 游戏实际显示区域: ${(designWidth * scale).toFixed(2)}x${(designHeight * scale).toFixed(2)}`);

        // 添加额外的调试信息
        console.log(`[Utils] 设备像素比: ${deviceInfo.pixelRatio}`);
        console.log(`[Utils] 设备平台: ${deviceInfo.platform}`);

        const adaptInfo = {
            scale: scale,
            offsetX: offsetX,
            offsetY: offsetY,
            actualWidth: screenWidth,
            actualHeight: screenHeight,
            // 添加更多调试信息
            scaleX: scaleX,
            scaleY: scaleY,
            designWidth: designWidth,
            designHeight: designHeight
        };

        console.log(`[Utils] 最终适配信息:`, adaptInfo);

        return adaptInfo;
    }

    /**
     * 播放音效
     */
    static playSound(soundPath) {
        try {
            const audio = wx.createInnerAudioContext();
            audio.src = soundPath;
            audio.play();
            
            audio.onError((res) => {
                console.log('音频播放失败:', res);
            });
            
            return audio;
        } catch (error) {
            console.log('创建音频上下文失败:', error);
            return null;
        }
    }

    /**
     * 显示提示消息
     */
    static showToast(title, icon = 'none', duration = 2000) {
        wx.showToast({
            title: title,
            icon: icon,
            duration: duration
        });
    }

    /**
     * 显示加载提示
     */
    static showLoading(title = '加载中...') {
        wx.showLoading({
            title: title
        });
    }

    /**
     * 隐藏加载提示
     */
    static hideLoading() {
        wx.hideLoading();
    }

    /**
     * 振动反馈
     */
    static vibrate(type = 'short') {
        try {
            if (type === 'long') {
                wx.vibrateLong();
            } else {
                wx.vibrateShort();
            }
        } catch (error) {
            console.log('振动失败:', error);
        }
    }

    /**
     * 保存数据到微信小游戏本地存储
     */
    static saveToStorage(key, data) {
        try {
            wx.setStorageSync(key, data);
            console.log(`数据已保存: ${key}`);
            return true;
        } catch (error) {
            console.log('保存数据失败:', error);
            return false;
        }
    }

    /**
     * 从微信小游戏本地存储读取数据
     */
    static loadFromStorage(key, defaultValue = null) {
        try {
            const data = wx.getStorageSync(key);
            if (data) {
                console.log(`数据已读取: ${key}`);
                return data;
            }
            return defaultValue;
        } catch (error) {
            console.log('读取数据失败:', error);
            return defaultValue;
        }
    }

    /**
     * 计算游戏得分
     */
    static calculateScore(baseScore, combo, difficulty = 1) {
        let score = baseScore * difficulty;
        
        // 连击加成
        if (combo > 1) {
            score += Math.floor(baseScore * combo * 0.1);
        }
        
        return Math.max(score, 1);
    }

    /**
     * 格式化时间显示
     */
    static formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }
}
